<template>
  <div class="modal fade" ref="editRef" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">{{ msg }}</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <Form ref="formRef" :schema="schema" @change="change"></Form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" @click="cancel()">取消</button>
          <button type="button" class="btn btn-primary" @click="submit()">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { PropType, defineComponent, ref, toRefs } from 'vue'
import { useModal } from '@/hooks';
import Form, { FormItem } from '../Form.vue';

export default defineComponent({
  props: {
    show: {
      type: Boolean,
      default: false
    },
    msg: {
      type: String as PropType<'编辑' | '新增'>,
      default: '新增'
    },
    schema: {
      type: Array as PropType<FormItem[]>,
      default: () => []
    }
  },
  components: {
    Form
  },
  emits: ['submit', 'update:show'],
  setup (_props, {emit}) {
    const { show } = toRefs(_props)
    const { modalRef: editRef, hide} = useModal(show, 'show')

    const formRef = ref();
    const formData = ref();

    // 取消
    const cancel = () => {
      hide();
      formData.value = null;
      formRef.value?.clearForm();
    }

    // 提交表单
    const submit = () => {
      emit('submit', formData.value);
      cancel();
    }

    return {
      editRef,
      cancel,
      submit,
      formRef,
      change: (val: any) => {
        formData.value = val
      }
    }
  }
})
</script>

<style scoped>

</style>
